package com.xique.park.command.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkIpcCommandApi;
import com.xique.park.command.handler.base.BaseCommand;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.ParkApiName;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 手动入场或出场
 *
 * @author WLD
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MarkCarInoutCommandHandler extends BaseCommand {

    private final IParkIpcCommandApi parkIpcCommandApi;

    /**
     * 车牌
     */
    private final ThreadLocal<String> plate = new ThreadLocal<>();

    /**
     * 进场或出场时间
     */
    private final ThreadLocal<String> inOrOutTime = new ThreadLocal<>();

    /**
     * 车辆类型
     */
    private final ThreadLocal<Integer> carType = new ThreadLocal<>();

    /**
     * 0：开闸，1：不开闸
     */
    private final ThreadLocal<Integer> isNoOpenGate = new ThreadLocal<>();

    @Override
    public String getServiceName() {
        return ParkApiName.COMMAND_MARK_CAR_IN_OR_OUT;
    }

    @Override
    public String getVersion() {
        return ParkApiName.VER_2_0;
    }

    @Override
    public AjaxResult issue(Long parkId, String sn, String cmd) {
        try {
            JSONObject baseObj = getBaseObj(sn, getServiceName(), getVersion());
            JSONObject dtObj = new JSONObject();
            dtObj.put("plate", plate.get());
            dtObj.put("platetype", carType.get());
            dtObj.put("is_no_open_gate", isNoOpenGate.get());
            dtObj.put("date", inOrOutTime.get());
            baseObj.put(CommandConstant.DATA, dtObj);

            @SuppressWarnings("unchecked")
            Map<String, Object> params = JSON.toJavaObject(baseObj, Map.class);

            AjaxResult issueResult = parkIpcCommandApi.issue(params);

            log.info("[停车系统]手动入场或出场命令下发，服务名：{}，版本号：{}，车场ID：{}，设备编号：{}，下发参数：{}，下发结果：{}",
                    getServiceName(), getVersion(), parkId, sn, params, issueResult);

            updateCommonInfo(cmd, params, issueResult);

            return issueResult;
        } finally {
            close();
        }
    }

    public void setPlate(String plate) {
        this.plate.set(plate);
    }

    public void setInOrOutTime(String inOrOutTime) {
        this.inOrOutTime.set(inOrOutTime);
    }

    public void setCarType(Integer carType) {
        this.carType.set(carType);
    }

    public void setIsNoOpenGate(Integer isNoOpenGate) {
        this.isNoOpenGate.set(isNoOpenGate);
    }

    private void close() {
        plate.remove();
        inOrOutTime.remove();
        carType.remove();
        isNoOpenGate.remove();
    }

}
